package aos.maekawa;

import java.util.Date;

import aos.maekawa.entity.Message;
import aos.maekawa.entity.MessageType;
import aos.maekawa.exception.AosException;
import aos.maekawa.log.LogUtils;

public class CSHandler implements Runnable {

	private int nodeId;
	private ProcessorNode processorNode;
	private Message msg;

	public CSHandler(ProcessorNode processorNode, Message msg) {
		this.processorNode = processorNode;
		this.nodeId = this.processorNode.getNodeId();
		this.msg = msg;
	}

	@Override
	public void run() {
		try {
			LogUtils.keyLog(msg.getFromId() + " " + msg.getReqId() + " "
					+ (new Date()) + " BEGIN");
			Thread.sleep(msg.getCst());
			LogUtils.keyLog(msg.getFromId() + " " + msg.getReqId() + " "
					+ (new Date()) + " END");
		} catch (InterruptedException e) {
			LogUtils.errorLog(e.getMessage());
		}
		Message respMsg = new Message();
		respMsg.setFromId(nodeId);
		respMsg.setToId(msg.getFromId());
		respMsg.setMsgType(MessageType.ACK);
		try {
			processorNode.sendMessage(respMsg);
		} catch (AosException e) {
			LogUtils.errorLog(e.getMessage());
		}
	}

}
